<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row :gutter="20">
        <!-- 搜索区域 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryObj.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 添加区域 -->
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="dataList" border stripe>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch
              @change="userState(scope.row)"
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template v-slot="scope">
            <!-- 修改按钮 -->
            <el-button
              @click="showEditDialog(scope.row.id)"
              type="primary"
              size="mini"
              icon="el-icon-edit"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              @click="deleteUserInfoById(scope.row.id)"
              type="danger"
              size="mini"
              icon="el-icon-delete"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip :enterable="false" effect="dark" content="分配角色" placement="top">
              <el-button
                @click="allowRolesDialog(scope.row)"
                type="warning"
                size="mini"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryObj.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryObj.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加对话框区域 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 内容底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑修改用户对话框区域 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      @close="setRoleDialogClosed"
      title="分配角色"
      :visible.sync="allowRoleDialogVisible"
      width="50%"
    >
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>
          分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allowRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allowRoleDialogClosed">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// 自定义手机号校验规则
var checkMobile = (rule, value, callback) => {
  const regMobile = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
  if (!regMobile.test(value)) {
    return callback(new Error("请输入合法的手机号"));
  }
  callback();
};
// 自定义邮箱校验规则
var checkEmail = (rule, value, callback) => {
  const regEmail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  if (!regEmail.test(value)) {
    return callback(new Error("请输入合法的邮箱号"));
  }
  callback();
};
export default {
  data() {
    return {
      queryObj: {
        query: "",
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      dataList: [],
      total: 0,
      addDialogVisible: false,
      // 对话框内表单数据对象
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 添加对话框内表单验证规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名在3到10个字符之间",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "密码长度在6到15位之间", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      // 关闭显示编辑表单对话框
      editDialogVisible: false,
      // 编辑表单数据
      editForm: {},
      // 修改表单用户规则对象
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      allowRoleDialogVisible: false,
      // 需要被分配权限角色的用户信息
      userInfo: {},
      // 角色列表数据
      roleList: [],
      // 被选中的角色id值
      selectedRoleId: ""
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryObj
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.dataList = res.data.users;
      this.total = res.data.total;
      this.pagenum = res.data.pagenum;
    },
    // 监听每页显示的条数改变
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.queryObj.pagesize = newSize;
      this.getUserList();
    },
    // 监听当前所在页码值改变的事件
    handleCurrentChange(currentChange) {
      // console.log(currentChange);
      this.queryObj.pagenum = currentChange;
      this.getUserList();
    },
    async userState(userInfo) {
      const { data: stateEditRes } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (stateEditRes.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        this.$message.error(stateEditRes.meta.msg);
      }
      this.$message.success("更新用户状态成功!");
    },
    // 添加用户框关闭后重置表单
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加用户信息
    addUser() {
      // 表单预校验
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        // 发送网络请求
        const { data: res } = await this.$http.post("users", this.addForm);
        console.log(res);

        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success("添加用户信息成功!");
        // 关闭对话框
        this.addDialogVisible = false;
        // 重新获取数据渲染页面
        this.getUserList();
      });
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`users/${id}`, this.editForm);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 提交修改用户信息
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `users/${this.editForm.id}`,
          {
            mobile: this.editForm.mobile,
            email: this.editForm.email
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("修改用户信息失败!");
        this.getUserList();
        this.$message.success("修改用户信息成功!");
        this.editDialogVisible = false;
      });
    },
    // 根据id删除用户
    async deleteUserInfoById(id) {
      const res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (res !== "confirm") return;
      // 发起网络请求删除用户
      const { data: result } = await this.$http.delete(`users/${id}`);
      if (result.meta.status !== 200)
        return this.$message.error("删除用户失败");
      this.$message.success("删除成功");
      // 判断页码值是否应该-1
      if (this.dataList.length == 1 && this.queryObj.pagenum > 1) {
        this.queryObj.pagenum--;
      }
      this.getUserList();
    },
    // 显示分配角色对话框
    async allowRolesDialog(userInfo) {
      this.userInfo = userInfo;
      // 在显示对话框之前,先获取角色列表的数据
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败!");
      this.roleList = res.data;
      this.allowRoleDialogVisible = true;
    },
    // 点击确认关闭分配角色对话框应该做的事
    async allowRoleDialogClosed() {
      // 判断选项框是否为空
      if (!this.selectedRoleId) return this.$message.error("请选择角色");
      // 发起网络请求
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        { rid: this.selectedRoleId }
      );
      if (res.meta.status !== 200) return this.$message.error("设置角色失败!");
      this.$message.success("设置角色成功!");
      this.getUserList();
      this.allowRoleDialogVisible = false;
    },
    // 监听设置角色对话框关闭事件
    setRoleDialogClosed() {
      this.userInfo = {};
      this.selectedRoleId = "";
    }
  }
};
</script>
<style lang="less" scoped>
</style>
